<template>
  <el-card :shadow="'never'">
    <el-tabs type="border-card">
      <el-tab-pane label="待审核">
        <el-collapse accordion>
          <div v-for="(items, type) in msgListRecent.audit" :key="type">
            <el-collapse-item :title="typeTrans[type]" :name="type">
              <div
                v-for="(item, index) in items"
                :key="index"
                class="sci_content"
              >
                <span
                  v-for="(value, key) in typeTableTrans[type]"
                  :key="key"
                  class="sci_value"
                >
                  <el-text tag="b" size="large"> {{ value }} : </el-text>
                  <a>{{ item[key] }}</a>
                </span>
                <div style="width: 100%; margin: auto; margin-top: 20px">
                  <el-steps style="max-width: 100%" :active="3" align-center>
                    <el-step
                      v-for="(step, index) in steps"
                      :key="index"
                      :title="step.title"
                      :status="getStepStatus(item.status, index)"
                    />
                  </el-steps>
                </div>
                <el-button type="primary" v-if="hasPermission('quash')">
                  <el-icon style="vertical-align: middle">
                    <Filter />
                  </el-icon>
                  <span style="vertical-align: middle"> 审查</span>
                </el-button>
                <el-button
                  type="primary"
                  v-if="hasPermission('preview') && item.path != ''"
                >
                  <el-icon style="vertical-align: middle">
                    <FullScreen />
                  </el-icon>
                  <span style="vertical-align: middle"> 预览文件</span>
                </el-button>
                <el-button
                  type="primary"
                  v-if="hasPermission('update')"
                  @click="updateSci(item, type)"
                >
                  <el-icon style="vertical-align: middle">
                    <Edit />
                  </el-icon>
                  <span style="vertical-align: middle"> 修改</span>
                </el-button>
                <a
                  v-if="hasPermission('approval', 'admin')"
                  style="margin-left: 13px"
                >
                  <el-button type="primary" @click="updateAdmin(item, type)">
                    <el-icon style="vertical-align: middle">
                      <CircleCheck />
                    </el-icon>
                    <span style="vertical-align: middle"> 更改状态</span>
                  </el-button>
                </a>
                <a v-else style="margin-left: 13px">
                  <el-popconfirm
                    title="确定要撤销此项?"
                    @confirm="_quash(item, type)"
                    v-if="hasPermission('quash') && item.status == 3"
                  >
                    <template #reference>
                      <el-button type="primary">
                        <el-icon style="vertical-align: middle">
                          <Remove />
                        </el-icon>
                        <span style="vertical-align: middle"> 撤销</span>
                      </el-button>
                    </template>
                  </el-popconfirm>
                  <el-popconfirm
                    title="确定要不通过此项?"
                    @confirm="updateMsg(0, item, type)"
                    v-if="hasPermission('approval')"
                  >
                    <template #reference>
                      <el-button type="primary">
                        <el-icon style="vertical-align: middle">
                          <CircleClose />
                        </el-icon>
                        <span style="vertical-align: middle"> 审批不通过</span>
                      </el-button>
                    </template>
                  </el-popconfirm>

                  <el-popconfirm
                    title="确定要通过此项?"
                    @confirm="updateMsg(1, item, type)"
                    v-if="hasPermission('approval')"
                  >
                    <template #reference>
                      <el-button type="primary">
                        <el-icon style="vertical-align: middle">
                          <CircleCheck />
                        </el-icon>
                        <span style="vertical-align: middle"> 审批通过</span>
                      </el-button>
                    </template>
                  </el-popconfirm>
                </a>
              </div>
            </el-collapse-item>
          </div>
        </el-collapse>
      </el-tab-pane>
      <el-tab-pane label="已退回">
        <el-collapse accordion>
          <div v-for="(items, type) in msgListRecent.reject" :key="type">
            <el-collapse-item :title="typeTrans[type]" :name="type">
              <div
                v-for="(item, index) in items"
                :key="index"
                class="sci_content"
              >
                <span
                  v-for="(value, key) in typeTableTrans[type]"
                  :key="key"
                  class="sci_value"
                >
                  <el-text tag="b" size="large"> {{ value }} : </el-text>
                  <a>{{ item[key] }}</a>
                </span>
                <div style="width: 100%; margin: auto; margin-top: 20px">
                  <el-steps
                    style="max-width: 100%"
                    :active="3"
                    align-center
                    process-status="success"
                  >
                    <el-step
                      v-for="(step, index) in steps"
                      :key="index"
                      :title="step.title"
                      :status="getStepStatus(item.status, index)"
                    />
                  </el-steps>
                </div>
                <el-button
                  type="primary"
                  v-if="hasPermission('update')"
                  @click="updateSci(item, type)"
                >
                  <el-icon style="vertical-align: middle">
                    <Edit />
                  </el-icon>
                  <span style="vertical-align: middle"> 修改</span>
                </el-button>
                <el-popconfirm
                  title="确定要删除此项?"
                  @confirm="_deleleMsg(item, type)"
                  v-if="hasPermission('delete')"
                >
                  <template #reference>
                    <el-button type="primary">
                      <el-icon style="vertical-align: middle">
                        <CircleClose />
                      </el-icon>
                      <span style="vertical-align: middle"> 删除</span>
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </el-collapse-item>
          </div>
        </el-collapse>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      v-model="updAdmDialogVisible"
      title="选择状态"
      width="500"
      align-center
    >
      <el-select
        filterable
        v-model="updAdmStatus"
        placeholder=" "
        style="width: 200px; margin-left: 30%"
      >
        <el-option label="已撤销" value="0" />
        <el-option label="部门退回" value="1" />
        <el-option label="校级退回" value="2" />
        <el-option label="部门审批" value="3" />
        <el-option label="校级审批" value="4" />
        <el-option label="已通过" value="5" />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="_updateMsg(parseInt(updAdmStatus))"
            >确认更改</el-button
          >
          <el-button type="primary" @click="updAdmDialogVisible = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 详细信息展示 -->
    <el-dialog
      v-model="control.centerDialogVisible"
      title="详细信息"
      width="750"
      align-center
    >
      <PaperConfForm
        v-if="formInlineType === 'PaperConf'"
        ref="paperConf"
        v-model:formInline="formInline"
        v-model:control="control"
        :hasPermission="hasPermission"
        :_loadQueryPage="_loadMsg"
      />
    </el-dialog>
  </el-card>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref } from "vue";
import * as $msgApi from "@/api/sci/msg";
import { ElMessage, ElMessageBox } from "element-plus";
import { useAuthStoreHook } from "@/store/modules/auth";
import PaperConfForm from "../modules/PaperConf-form.vue";
const typeTrans = {
  PaperConf: "会议论文",
  PaperJour: "期刊论文",
  AcaCom: "学术交流",
  AcaDes: "学术称号",
  AchCov: "成果转化",
  AchSet: "智库建设",
  HorApp: "获批项目",
  HorFin: "结项验收",
  IntPat: "获批专利",
  IntSoft: "软件著作",
  ManTeam: "人才团队",
  ManPlat: "平台管理",
  SchAward: "获批奖励",
  SchShow: "音美展览",
  SchSport: "体育比赛",
  VerApp: "获批项目",
  VerFin: "结项验收",
  WorkLearn: "学术著作"
};
const typeTableTrans = {
  PaperConf: {
    department: "院系部门",
    nickname: "姓名",
    username: "工号",
    title: "题目",
    firstAuthor: "第一作者",
    otherAuthor: "其他作者",
    confName: "会议名称",
    spot: "会议地点",
    confTime: "会议时间",
    level: "会议级别",
    press: "出版社",
    type: "收录类别",
    textNumber: "字数（千）",
    bonus: "科研奖金（万）",
    point: "业绩点",
    remark: "备注",
    modified: "审核时间",
    modifiedBy: "审核者",
    created: "申请时间",
    createdBy: "申请者",
    proposal: "审批意见"
  },
  PaperJour: {
    department: "院系部门",
    nickname: "姓名",
    username: "工号",
    title: "题目",
    firstAuthor: "第一作者",
    otherAuthor: "其他作者",
    jourName: "会议名称",
    volume: "卷期号",
    page: "页码",
    jourTime: "期刊时间",
    textNumber: "字数（千）",
    bonus: "科研奖金（万）",
    point: "业绩点",
    level: "分区",
    impactFactor: "影响因子",
    remark: "备注",
    modified: "审核时间",
    modifiedBy: "审核者",
    created: "申请时间",
    createdBy: "申请者",
    proposal: "审批意见"
  }
};
const msgListRecent = reactive({
  audit: {},
  reject: {}
});
const approvalStatus = reactive({
  pass: 0,
  reject: 0
});
const formMsg = reactive({
  id: "",
  proposal: "",
  type: "",
  sciId: ""
});
const steps = [{ title: "教师" }, { title: "院级部门" }, { title: "校级部门" }];
//增改表单数据
const formInline = reactive({
  id: "",
  status: 0,
  textNumber: 0,
  bonus: 0,
  confName: "",
  confTime: "",
  department: "",
  firstAuthor: "",
  level: "",
  modified: "",
  nickname: "",
  otherAuthor: "",
  path: "",
  point: "",
  press: "",
  remark: "",
  spot: "",
  title: "",
  type: "",
  username: ""
});
// const _loadQueryPage = () => {};
const formInlineType = ref(null);
const control = reactive({
  isLook: true,
  isAdd: false,
  centerDialogVisible: false
});
const paperConf = ref(null);
const updateSci = (item, type) => {
  control.centerDialogVisible = true;
  console.log(item);
  formInlineType.value = type;
  nextTick(() => {
    Object.keys(formInline).forEach(key => {
      if (Reflect.has(item, key)) {
        formInline[key] = item[key];
      }
    });
    formInline.id = item.sciId;
    formInline.confTime = item.confTime.split(" ")[0];
    console.log(formInline);
  });
};
const updateMsg = (isPass, item, type) => {
  formMsg.sciId = item.sciId;
  formMsg.id = item.id;
  formMsg.type = type;
  // console.log(formMsg);
  // 动态设置提示框的内容
  const promptMessage = isPass
    ? "请输入审批意见（非必填）"
    : "请输入审批意见（必填）";
  const inputPattern = isPass ? /.*/ : /.+/; // 如果是必填，要求输入非空内容
  const inputErrorMessage = isPass ? "" : "审批意见不能为空"; // 必填时提供错误提示

  ElMessageBox.prompt(promptMessage, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    inputPattern: inputPattern,
    inputErrorMessage: inputErrorMessage
  })
    .then(({ value }) => {
      formMsg.proposal = value;
      const status = isPass ? approvalStatus.pass : approvalStatus.reject;
      _updateMsg(status);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "输入已取消"
      });
    });
};
const _updateMsg = status => {
  $msgApi
    .update(status, formMsg)
    .then(res => {
      if (res.success) {
        ElMessage({
          message: "审批成功",
          type: "success"
        });
      }
    })
    .catch(error => {
      ElMessage({
        message: error.message || "添加失败，请检查网络或稍后再试。",
        type: "error"
      });
    })
    .finally(() => {
      _loadMsg();
      updAdmDialogVisible.value = false;
    });
};
const _deleleMsg = async (item, type) => {
  await new Promise(resolve => {
    formMsg.sciId = item.sciId;
    formMsg.id = item.id;
    formMsg.type = type;
    resolve(true); // 明确告知赋值完成
  });
  $msgApi
    .delQuash(formMsg)
    .then(res => {
      if (res.success) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
      }
    })
    .catch(error => {
      ElMessage({
        message: error.message || "删除失败，请检查网络或稍后再试。",
        type: "error"
      });
    })
    .finally(() => {
      _loadMsg();
    });
};
//撤销
const _quash = async (item, type) => {
  // 确保赋值操作完成后再继续
  await new Promise(resolve => {
    formMsg.sciId = item.sciId;
    formMsg.id = item.id;
    formMsg.type = type;
    resolve(true); // 明确告知赋值完成
  });

  $msgApi
    .update(0, formMsg)
    .then(res => {
      if (res.success) {
        ElMessage({
          message: "撤销成功",
          type: "success"
        });
      }
    })
    .catch(error => {
      ElMessage({
        message: error.message || "撤销失败，请检查网络或稍后再试。",
        type: "error"
      });
    })
    .finally(() => {
      _loadMsg();
    });
};
// 审批步骤状态处理
const getStepStatus = (
  status: number,
  stepIndex: number
): "" | "error" | "success" | "wait" | "finish" | "process" => {
  const stepStatuses: (
    | ""
    | "error"
    | "success"
    | "wait"
    | "finish"
    | "process"
  )[][] = [
    ["error", "wait", "wait"], // status = 0
    ["success", "error", "wait"], // status = 1
    ["success", "success", "error"], // status = 2

    ["success", "wait", "wait"], // status = 3
    ["success", "success", "wait"] // status = 4
  ];

  if (status < 0 || status > 4) {
    console.warn("Invalid status value:", status);
    return "error";
  }
  return stepStatuses[status][stepIndex];
};
//用户权限列表
const permissionList = ref([]);
// 加载数据
const _loadData = () => {
  _loadMsg();
  //持久化用户权限
  _loadPermission();
};
const _loadMsg = () => {
  $msgApi.msgListRecent().then((res: any) => {
    if (res.success) {
      msgListRecent.audit = res.result.audit || {};
      msgListRecent.reject = res.result.reject || {};
    }
  });
};
const _loadPermission = () => {
  permissionList.value = useAuthStoreHook().getPermission();
  if (hasPermission.value("approval", "user")) {
    approvalStatus.pass = 3;
    approvalStatus.reject = 0;
  } else if (hasPermission.value("approval", "dep_head")) {
    approvalStatus.pass = 4;
    approvalStatus.reject = 1;
  } else if (hasPermission.value("approval", "sch_head")) {
    approvalStatus.pass = 5;
    approvalStatus.reject = 2;
  }
};
//权限验证函数
const hasPermission = computed(() => {
  return (...types: string[]) => {
    const permissionKey = `sci:paper:conference:${types.join(":")}`;
    return permissionList.value.includes(permissionKey);
  };
});
const updAdmStatus = ref(null);
const updAdmDialogVisible = ref(false);
const updateAdmin = (item, type) => {
  formMsg.sciId = item.sciId;
  formMsg.id = item.id;
  formMsg.type = type;
  updAdmDialogVisible.value = true;
};
onMounted(() => {
  _loadData();
});
</script>

<style lang="css">
.el-collapse-item__header {
  margin-left: 45%;
  font-size: 25px;
}
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.sci_content {
  display: flex;
  flex-wrap: wrap;
  background-color: #f5f7fa;
  margin-bottom: 30px;
}
.sci_value {
  /* margin-left: 10%; */
  margin-right: 10%;
  min-width: 250px;
  font-size: 18px;
}
.sci_value a {
  font-family: "楷体", "楷体_GB2312";
}
</style>
